package com.parktech.sun.utils.action;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

public class BDom4j {
	
	private static final Log LOG = LogFactory.getLog(BDom4j.class);
	
    /** XML文件路径 */
    private String XMLPath = null;

    /** XML文档 */
    private Document document = null;

    private OutputFormat m_format = null;

    private Element m_root = null;
    /**
     * @return Returns the m_root.
     */
    public Element getM_root() {
        return m_root;
    }
    /**
     * @param m_root The m_root to set.
     */
    public void setM_root(Element m_root) {
        this.m_root = m_root;
    }
    
    
    public BDom4j() {
    }

    /**
     * 初始化xml文件
     * @param XMLPath 文件路径
     */
    public BDom4j(String XMLPath) {
        this.XMLPath = XMLPath;
    }
    

    public void openXML(Document doc){
    	m_format = OutputFormat.createPrettyPrint();
        m_format.setEncoding("GBK");
        this.document = doc;
        m_root = this.document.getRootElement();
        //System.out.println("openXML() successful ...");
    }
    
    /**
     * 打开文档
     */
    public void openXML() {
        try {
        	m_format = OutputFormat.createPrettyPrint();
            m_format.setEncoding("GBK");
            SAXReader reader = new SAXReader();
            this.document = reader.read(this.XMLPath);
            m_root = this.document.getRootElement();
            //System.out.println("openXML() successful ...");
        } catch (Exception e) {
        	LOG.error(e);
            //System.out.println("openXML() Exception:" + e.getMessage());
        }
    }
    
    public void parseXML(String xmlContent)throws Exception{
    	m_format = OutputFormat.createPrettyPrint();
        m_format.setEncoding("GBK");
    	 this.document= DocumentHelper.parseText(xmlContent);
    	 m_root = this.document.getRootElement();
    }
    
    public void openXML(InputStream input){
        try {
        	m_format = OutputFormat.createPrettyPrint();
            m_format.setEncoding("GBK");
            SAXReader reader = new SAXReader();
            this.document = reader.read(input);
            m_root = this.document.getRootElement();
            //System.out.println("openXML() successful ...");
        } catch (Exception e) {
        	LOG.error(e);
            //System.out.println("openXML() Exception:" + e.getMessage());
        }
    }

    /**
     * 创建文档
     * @param rootName 根节点名称
     */
    public void createXML(String rootName) {
        try {
            this.document = DocumentHelper.createDocument();
            m_format = OutputFormat.createPrettyPrint();
            m_format.setEncoding("GBK");
            m_root = document.addElement(rootName);
            //System.out.println("createXML() successful...");
        } catch (Exception e) {
        	LOG.error(e);
            //System.out.println("createXML() Exception:" + e.getMessage());
        }
    }

    /**
     * 获取指定名称的元素，返回一列表
     * @param specName
     * @return
     */
    @SuppressWarnings("unchecked")
	public List getSpecNameElementList(String specName) {
        return m_root.selectNodes(specName);
    }

    /**
     * 获取指定名称的元素
     * @param specName
     * @return
     */
    public Node getSpecNameElement(String specName) {
        return m_root.selectSingleNode(specName);
    }

    /**
     * 把一新元素插入到指定的元素中
     * @param parentEle  父元素
     * @param eleName  新插入的元素名
     * @param eleText 新插入的元素文本值
     * @param attributes  新插入的元素的属性集
     */
    @SuppressWarnings("unchecked")
	public Element addElementInSpecEle(Element parentEle, String eleName,
            String eleText, HashMap attributes) {
        Element ele = parentEle.addElement(eleName);
        if (StringUtils.isNotBlank(eleText))
            ele.setText(eleText);
        if (attributes != null) {
            Iterator it = attributes.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                String value = (String) attributes.get(key);
                if(StringUtils.isNotBlank(value))
                	ele.addAttribute(key, value);
                
            }
        }
        return ele;
    }

    /**
     * 添加根节点的child
     * @param nodeName 节点名
     * @param nodeValue 节点值
     */
    @SuppressWarnings("unchecked")
	public Element addNodeFromRoot(String nodeName,String nodeValue,HashMap attributes) {
        Element level1 = m_root.addElement(nodeName);
        if(StringUtils.isNotBlank(nodeValue))
            level1.addText(nodeValue);
        if (attributes != null) {
            Iterator it = attributes.keySet().iterator();
            while (it.hasNext()) {
                String key = (String) it.next();
                String value = (String) attributes.get(key);
                level1.addAttribute(key, value);
            }
        }
        return level1;
    }

    /**
     * 打开文档
     * @param filePath 文档路径
     */
    public void openXML(String filePath) {
        try {
            SAXReader saxReader = new SAXReader();
            this.document = saxReader.read(filePath);
            //System.out.println("openXML(String filePath) successful ...");
        } catch (Exception e) {
        	LOG.error(e);
            //System.out.println("openXML() Exception:" + e.getMessage());
        }
    }

    /**
     * 保存文档
     */
    public void saveXML() {
    	try {
            XMLWriter output = new XMLWriter(new FileWriter(new File(XMLPath)),m_format);
            output.write(document);
            output.close();
            //System.out.println("saveXML() successful ...");
        } catch (Exception e1) {
        	LOG.error(e1);
            //System.out.println("saveXML() Exception:" + e1.getMessage());
        }
    }
    
    
    public InputStream saveXml2()throws Exception{
    	try {
            XMLWriter output = new XMLWriter(new FileWriter(new File(XMLPath)),m_format);
            output.write(document);
            output.close();
            //System.out.println("saveXML() successful ...");
        } catch (Exception e1) {
            //System.out.println("saveXML() Exception:" + e1.getMessage());
        }
    	return new FileInputStream(new File(XMLPath));
    }
    
    
    /**
     * 把dom4j document对象保存至文件。
     * @param document
     * @param strFullName
     * @throws Exception
     */
    public static void documentToFile(Document document,String strFullName,String encode) throws Exception{
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(encode);
        XMLWriter output = null;
        try{
	        File file = new File(strFullName);
	        output = new XMLWriter(new FileWriter(file), format);
	        output.write(document);
	        output.close();
        }
        catch(Exception ex){
        	LOG.error(ex);
        	throw new Exception("Dom文档保存至文件" + strFullName + "失败:" + ex.getMessage());
        }
        finally{
        	if(output != null)
        		output.close();
        }
    }
    
    /**
     * 保存文档
     * @param toFilePath 保存路径
     *//*
    public void saveXML(String toFilePath) {
        try {
            XMLWriter output = new XMLWriter(new FileWriter(
                    new File(toFilePath)));
            output.write(document);
            output.close();
        } catch (Exception e1) {
            //System.out.println("saveXML() Exception:" + e1.getMessage());
        }
    }*/
    
    
    /**
     * 以InputStream的类型导本当前的Xml
     */
    public InputStream exportXml()throws Exception{
        return  new FileInputStream(new File(XMLPath));
    }
    /**
     * 获得某个节点的值
     * @param nodeName 节点名称
     */
    public String getElementValue(String nodeName) {
        try {
            Node node = document.selectSingleNode("//" + nodeName);
            return node.getText();
        } catch (Exception e1) {
            System.out
                    .println("getElementValue() Exception：" + e1.getMessage());
            return null;
        }
    }
    
    public String getElementValueByPath(String nodePath) {
            Node node = document.selectSingleNode(nodePath);
            return node.getText();
//            try {
//        } catch (Exception e1) {
//        	LOG.error(e1);
//            System.out
//                    .println("getElementValue() Exception：" + e1.getMessage());
//            return null;
//        }
    }
    
    @SuppressWarnings("unchecked")
	public List getElementList(String nodeName) {
        try {
            List list = document.selectNodes("//" + nodeName);
            return list;
        } catch (Exception e1) {
            System.out
                    .println("getElementValue() Exception：" + e1.getMessage());
            return null;
        }
    }

    /**
     * 获得某个节点的子节点的值
     * @param nodeName
     * @param childNodeName
     * @return
     */
    public String getElementValue(String nodeName, String childNodeName) {
        try {
            Node node = this.document.selectSingleNode("//" + nodeName + "/"
                    + childNodeName);
            return node.getText();
        } catch (Exception e1) {
        	LOG.error(e1);
            System.out
                    .println("getElementValue() Exception：" + e1.getMessage());
            return null;
        }
    }

    /**
     * 设置一个节点的text
     * @param xpath
     * @param nodeValue 节点值
     */
    public void setXPathElementValue(String xpath, String nodeValue) {
        try {
            Node node = this.document.selectSingleNode(xpath);
            node.setText(nodeValue);
        } catch (Exception e1) {
        	LOG.error(e1);
            System.out
                    .println("setElementValue() Exception:" + e1.getMessage());
        }
    }

    /**
     * 设置一个节点的text
     * @param nodeName 节点名
     * @param nodeValue 节点值
     */
    public void setElementValue(String nodeName, String nodeValue) {
        try {
            Node node = this.document.selectSingleNode("//" + nodeName);
            node.setText(nodeValue);
        } catch (Exception e1) {
        	LOG.error(e1);
            System.out
                    .println("setElementValue() Exception:" + e1.getMessage());
        }
    }

    /**
     * 设置一个节点值
     * @param nodeName 父节点名
     * @param childNodeName 节点名
     * @param nodeValue 节点值
     */
    public void setElementValue(String nodeName, String childNodeName,
            String nodeValue) {
        try {
            Node node = this.document.selectSingleNode("//" + nodeName + "/"
                    + childNodeName);
            node.setText(nodeValue);
        } catch (Exception e1) {
        	LOG.error(e1);
            //System.out.println("setElementValue() Exception:" + e1.getMessage());
        }
    }

    /**
	 * 
	 * @param is
	 * @return
	 */
	public final static Document InputStream2Docment(InputStream is) throws Exception {
		SAXReader saxReader = new SAXReader();
		Document document = null;
		document = saxReader.read(is);
		return document;
	}
	public Document getDocument() {
		return document;
	}
	public void setDocument(Document document) {
		this.document = document;
	}
	
}

